﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using dhDataAcess.produceDAL;
using dhSystemBLL.produceBLL;
using dhSystemBLL.basicData;
using baseSet.importExport;
using dhDataAcess.dataAcess.produceDataSetTableAdapters;
using dhDataAcess.dataAcess;
using baseSet;
using dhDataAcess.produceLinq;
using dhDataAcess.baseBLL;
using dhSystemBLL.orderData;
using dhsystem.Main;
using FastReport;

namespace dhsystem.produceForm
{
    public partial class FrmpackStockInMasterAdd : Form
    {
        produceDataSet.packStockInDetailDataTable packStockInDetailTable = new produceDataSet.packStockInDetailDataTable();
        packStockInDetailModel packStockInDetailRow = new packStockInDetailModel();
        packStockInBLL packStockIn = new packStockInBLL();

        deptBLL dept = new deptBLL();
        stockListBLL stockList = new stockListBLL();
        workerListBLL workerList = new workerListBLL();
       // packStockInMasterModel packStockInMasterRow = new packStockInMasterModel();
        produceDataSet.packStockInMasterDataTable packMasterTable = new produceDataSet.packStockInMasterDataTable();
        BindingSource b2;
        string state;
        string stockName;
        public FrmpackStockInMasterAdd(BindingSource b1, string _state,string _stockName)
        {
            InitializeComponent();
            state = _state;
            b2 = b1;
            stockName = _stockName;
        }
        //打开窗口时绑定数据
        private void FrmpackStockInMasterAdd_Load(object sender, EventArgs e)
        {
            textstockname.Text = stockName;
            bindingSourcedeptList.DataSource = dept.getdeptListAll();
            comboBoxdeptNum.DataSource = bindingSourcedeptList;
            comboBoxdeptNum.DisplayMember = "deptName";
            comboBoxdeptNum.ValueMember = "deptNum";
            bindingSourceworkerList.DataSource = workerList.getworkerListAll();
            comboBoxworkername.DataSource = bindingSourceworkerList;
            comboBoxworkername.DisplayMember = "name";
            comboBoxworkername.ValueMember = "workerNum";
            comboBoxdeptNum.Text = "包装部";
            //bindingSourcestockList.DataSource = stockList.getstockListAll();
            //comboBoxstockname.DataSource = bindingSourcestockList;
            //comboBoxstockname.DisplayMember = "stockName";
            //comboBoxstockname.ValueMember = "stockName";

            if (state == "新增")
            {
                textbillNo.Text = "P" + GlobalInfo.Date + "-" + basicSql.getOrderSerail("包装入库单号");
                bindingSourcepackStockInDetail.DataSource = packStockIn.getspackStockInDetailAllBybillNo(textbillNo.Text);
                dGridDetail.DataSource = bindingSourcepackStockInDetail;


            }
            if (state == "编辑")
            {
                comboBoxdeptNum.DataBindings.Add("text", b2, "deptNum");
                comboBoxworkername.DataBindings.Add("SelectedValue", b2, "workername");
                textbillNo.DataBindings.Add("text", b2, "billNo");
                dateTimebillDate.DataBindings.Add("value", b2, "billDate");
                textstockname.DataBindings.Add("text", b2, "stockname");
                textmark.DataBindings.Add("text", b2, "mark");
                bindingSourcepackStockInDetail.DataSource = packStockIn.getspackStockInDetailAllBybillNo(textbillNo.Text);
                dGridDetail.DataSource = bindingSourcepackStockInDetail;
            }
            DcolumnSet.colSet(moduleInfo.packStockInDetail , dGridDetail);
            dGridDetail.AllowUserToAddRows = false;
            dGridDetail.AllowUserToAddRows = true;
            this.KeyPreview = true;
            dGridDetail.EditMode = DataGridViewEditMode.EditOnEnter;
            comboBoxdeptNum.Text = "包装部";

        }
        int i = 0;
        //保存按钮，插入或修改数据
        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (textbillNo.Text == "")
            {
                MessageBox.Show("请输入库单号");
            }
            else
            {
                try
                {
                    DialogResult result = MessageBox.Show("是否保存包装入库表信息！", "提示信息", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {

                        if (i == 0 && state == "新增")
                        {
                            state = "新增";
                        }
                        else
                        {
                            state = "编辑";
                        }
                        i++;
                        produceDataSet.packStockInMasterRow packStockInMasterRow = packMasterTable.NewpackStockInMasterRow();
                        dhDataAcess.dataAcess.produceDataSet.packStockInDetailDataTable ptable = (dhDataAcess.dataAcess.produceDataSet.packStockInDetailDataTable)bindingSourcepackStockInDetail.DataSource;
                        packStockInMasterRow.billNo = textbillNo.Text;
                        packStockInMasterRow.deptNum = comboBoxdeptNum.SelectedValue.ToString();
                        packStockInMasterRow.workername = comboBoxworkername.SelectedValue.ToString();
                        packStockInMasterRow.billDate = dateTimebillDate.Value;
                        packStockInMasterRow.billStatus = "包装中";
                        packStockInMasterRow.Status  = "新建";
                        packStockInMasterRow.stockName = textstockname.Text ;
                        packStockInMasterRow.createDate = DateTime.Now;
                        packStockInMasterRow.createUser = GlobalInfo.UserName;
                        packStockInMasterRow.updateDate = DateTime.Now;
                        packStockInMasterRow.updateUser = GlobalInfo.UserName;
                        packStockInMasterRow.mark = textmark.Text;
                        packMasterTable.AddpackStockInMasterRow(packStockInMasterRow);
                        packStockIn.packStockInInsert(packMasterTable, ptable, state, textbillNo.Text, GlobalInfo.Date);
                        ptable.AcceptChanges();
                        bindingSourcepackStockInMaster.DataSource = packStockIn.getpackStockInMasterAll();

                        if (Convert.ToDecimal(basicSql.getV_packInSUM(dGridDetail.CurrentRow.Cells["orderDetailNo"].Value.ToString())) >= Convert.ToDecimal(basicSql.getqtybyorderDetail(dGridDetail.CurrentRow.Cells["orderDetailNo"].Value.ToString())))
                        {
                            basicSql.getpackStockInMasterbillStatusUpdate(dGridDetail.CurrentRow.Cells["orderDetailNo"].Value.ToString(), "包装完成");
                        }
                        MessageBox.Show("保存成功");
                    }
                }
                catch (FormatException ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }

        }
        //取消按钮
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //添加子件
        private void buttAdd_Click(object sender, EventArgs e)
        {
            FrmpackStockInDetailAdd packStockInDetail = new FrmpackStockInDetailAdd (bindingSourcepackStockInDetail, "新增", textbillNo.Text);
            packStockInDetail.ShowDialog();
        }
        //编辑子件
        private void buttedit_Click(object sender, EventArgs e)
        {
            FrmpackStockInDetailAdd packStockInDetail = new FrmpackStockInDetailAdd(bindingSourcepackStockInDetail, "编辑", textbillNo.Text);
            packStockInDetail.ShowDialog();
        }
        //删除子件
        private void buttDel_Click(object sender, EventArgs e)
        {

            try
            {
                string id = dGridDetail.Rows[dGridDetail.CurrentRow.Index].Cells[0].Value.ToString();
                DialogResult result = MessageBox.Show("是否删除：" + id + "！", "提示信息", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    dGridDetail.Rows.Remove(dGridDetail.CurrentRow);
                   
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        //选择入库部门
        private void buttuserselect_Click(object sender, EventArgs e)
        {
            string field;
            field = "deptNum";
            Frmprodutselect productselect = new Frmprodutselect(moduleInfo.deptList, field);
            DialogResult result = productselect.ShowDialog();
            if (result == DialogResult.Yes)
            {
                comboBoxdeptNum.SelectedValue = productselect.pname;
            }
        }
        //选择入库人
        private void button1_Click(object sender, EventArgs e)
        {
            string field;
            field = "workerNum";
            Frmprodutselect productselect = new Frmprodutselect(moduleInfo.workerList, field);
            DialogResult result = productselect.ShowDialog();
            if (result == DialogResult.Yes)
            {
                comboBoxworkername.SelectedValue = productselect.pname;
            }
        }

        private void 复制选中的内容ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            try
            {
                if (dGridDetail.Rows.Count != 0)
                {
                    produceDataSet.packStockInDetailDataTable detailTable = (produceDataSet.packStockInDetailDataTable)bindingSourcepackStockInDetail.DataSource;
                    produceDataSet.packStockInDetailRow  insertRow = detailTable.NewpackStockInDetailRow();
                    int recordID = Convert.ToInt32(dGridDetail.CurrentRow.Cells["recordID"].Value.ToString());
                    produceDataSet.packStockInDetailRow crreentRow = detailTable.FindByrecordid(recordID);
                    insertRow.billNo = crreentRow.billNo;
                    insertRow.boxno = crreentRow.boxno + 1;
                    if (!crreentRow.IsJweightNull())
                    {
                        insertRow.Jweight = crreentRow.Jweight;
                    }
                    else { insertRow.Jweight = 0; }
                    if (!crreentRow.IsmarkNull())
                    {
                        insertRow.mark = crreentRow.mark;
                    }
                    else { insertRow.mark = ""; }
                    if (!crreentRow.IsMweightNull ())
                    {
                        insertRow.Mweight = crreentRow.Mweight;
                    }
                    else { insertRow.Mweight = 0; }
                    insertRow.orderDetailNo = crreentRow.orderDetailNo;
                    insertRow.pName = crreentRow.pName;
                    if (!crreentRow.IsqtyNull())
                    {
                        insertRow.qty = crreentRow.qty;
                    }
                    else { insertRow.qty = 0; }
                    insertRow.qtywc = Convert.ToDecimal(dGridDetail.CurrentRow.Cells["qtywc"].Value.ToString()) + Convert.ToDecimal(dGridDetail.CurrentRow.Cells["qty"].Value.ToString());
                    insertRow.qtysy = Convert.ToDecimal(dGridDetail.CurrentRow.Cells["qtysy"].Value.ToString()) - Convert.ToDecimal(dGridDetail.CurrentRow.Cells["qty"].Value.ToString());
                    //if (!crreentRow.IsqtysyNull())
                    //{
                    //    insertRow.qtysy = crreentRow.qtysy;
                    //}
                    //else { insertRow.qtysy = 0; }
                    //if (!crreentRow.IsqtywcNull ())
                    //{
                    //    insertRow.qtywc = crreentRow.qtywc;
                    //}
                    //else { insertRow.qtywc = 0; }
                    if (!crreentRow.IsunitNull())
                    {
                        insertRow.unit = crreentRow.unit;
                    }
                    else { insertRow.unit = ""; }
                    detailTable.AddpackStockInDetailRow (insertRow);
                    bindingSourcepackStockInDetail.MoveLast();
                    bindingSourcepackStockInDetail.EndEdit();
                }
                else
                {
                    MessageBox.Show("不存在需要复制的行");
                }
            }
            catch (Exception )
            {
                MessageBox.Show("请选择要复制的行");
            }
        }

        private void dGridDetail_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            string field;
            field = "orderDetailNo";
            int colIndex = dGridDetail.Columns["orderDetailNo"].Index;
            int colIndexmark = dGridDetail.Columns["mark"].Index;
            if (colIndex == e.ColumnIndex)
            {
                Frmprodutselect select = new Frmprodutselect(moduleInfo.orderDetail,field);
                DialogResult result = select.ShowDialog();
                if (result == DialogResult.Yes)
                {

                    dGridDetail.CurrentCell.Value = select.pname;
                }
            }
            if (colIndexmark == e.ColumnIndex)
            {
                Frmmark mark = new Frmmark();
                DialogResult result = mark.ShowDialog();
                if (result == DialogResult.Yes)
                {

                    dGridDetail.CurrentCell.Value = mark.mark;
                }
            }
        }
        /// <summary>  
        /// 设置编辑状态下按回车键，跳到指定单元格.  
        /// </summary>  
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            string field;
            field = "orderDetailNo";
            //cValue = dGridDetail.CurrentRow.Cells[3].EditedFormattedValue.ToString();
            if (keyData == Keys.Enter)    //监听回车事件   
            {
                if (this.dGridDetail.IsCurrentCellInEditMode)   //如果当前单元格处于编辑模式   
                {

                    if (this.dGridDetail.CurrentCell.ColumnIndex == 2)
                    {
                        //cValue= dGridDetail.CurrentRow.Cells[3].EditedFormattedValue.ToString();
                        Frmprodutselect select = new Frmprodutselect(moduleInfo.orderDetail , field);
                        DialogResult result = select.ShowDialog();
                        if (result == DialogResult.Yes)
                        {
                            //dGridDetail.CurrentCell.Value = select.pname;

                            dGridDetail.CurrentRow.Cells["orderDetailNo"].Value = select.pname;
                            //dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[4];
                        }
                    }

                    if (this.dGridDetail.CurrentCell.ColumnIndex != 12)
                    {
                        SendKeys.Send("{Up}");
                        SendKeys.Send("{Tab}");
                        // SendKeys.Send("{Tab}");
                    }

                    else
                    {
                        SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}");
                        SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}"); SendKeys.Send("{LEFT}");
                    }
                }
                else
                {
                    SendKeys.Send("{Up}");
                    SendKeys.Send("{Tab}");
                    //SendKeys.Send("{Tab}");
                    //SendKeys.Send("{Tab}");
                }


            }

            if (keyData == Keys.F3)
            {
                int cRowIndex = dGridDetail.CurrentCell.RowIndex;
                int cCellIndex = dGridDetail.CurrentCell.ColumnIndex;
                dGridDetail.CurrentCell.Value = dGridDetail.Rows[cRowIndex - 1].Cells[cCellIndex].Value;
                if (cCellIndex == 2 || cCellIndex == 0)
                {
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex + 3];
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex];
                }
                else
                {
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex - 1];
                    dGridDetail.CurrentCell = dGridDetail.CurrentRow.Cells[cCellIndex];
                }
            }

            //继续原来base.ProcessCmdKey中的处理   
            return base.ProcessCmdKey(ref msg, keyData);

        }

        private void dGridDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
           
            if (dGridDetail.Rows.Count > 0 && e.RowIndex >= 0)
            {
                DataGridViewRow row = dGridDetail.Rows[e.RowIndex];
                if (row.Cells[e.ColumnIndex].OwningColumn.Name == "orderDetailNo" )
                {
                    row.Cells["billNo"].Value = textbillNo.Text;
                    row.Cells["pName"].Value = basicSql.getpnamebyorderDetail(row.Cells["orderDetailNo"].Value.ToString());
                    row.Cells["unit"].Value = basicSql.getunitbyorderDetail(row.Cells["orderDetailNo"].Value.ToString());
                    row.Cells["boxno"].Value = basicSql.getcountbyorderDetail(row.Cells["orderDetailNo"].Value.ToString())+1;
                 
                    //row.Cells["qtysy"].Value = Convert.ToString(Convert.ToDouble(basicSql.getqtybyorderDetail(row.Cells["orderDetailNo"].Value.ToString()));

                    if (basicSql.getstockQtyKG(row.Cells["orderDetailNo"].Value.ToString()) == "0")
                    {
                        row.Cells["qtywc"].Value = "0";
                        row.Cells["qtysy"].Value = Convert.ToString(Convert.ToDouble(basicSql.getqtybyorderDetail(row.Cells["orderDetailNo"].Value.ToString()) == ""));
                    }
                    else
                    {

                        row.Cells["qtywc"].Value = basicSql.getstockQtyKG(row.Cells["orderDetailNo"].Value.ToString());
                        row.Cells["qtysy"].Value = Convert.ToString(Convert.ToDouble(basicSql.getqtybyorderDetail(row.Cells["orderDetailNo"].Value.ToString())) - Convert.ToDouble(row.Cells["qtywc"].Value.ToString()));
                    }
                    
                
                }
                 if ( row.Cells[e.ColumnIndex].OwningColumn.Name == "qty")
                {

                    row.Cells["qtywc"].Value = Convert.ToDouble(row.Cells["qtywc"].Value.ToString()) + Convert.ToDouble(row.Cells["qty"].Value.ToString());
                    row.Cells["qtysy"].Value = Convert.ToDouble(row.Cells["qtysy"].Value.ToString()) - Convert.ToDouble(row.Cells["qty"].Value.ToString());
                 }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textbillNo.Text = "P" + GlobalInfo.Date + "-" + basicSql.getOrderSerail("包装入库单号");
            bindingSourcepackStockInDetail.DataSource = packStockIn.getspackStockInDetailAllBybillNo(textbillNo.Text);
            dGridDetail.DataSource = bindingSourcepackStockInDetail;
            textstockname.Text = "多余正品仓";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textbillNo.Text = "P" + GlobalInfo.Date + "-" + basicSql.getOrderSerail("包装入库单号");
            bindingSourcepackStockInDetail.DataSource = packStockIn.getspackStockInDetailAllBybillNo(textbillNo.Text);
            dGridDetail.DataSource = bindingSourcepackStockInDetail;
            textstockname.Text = "成品废品仓";
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            foreach (DataGridViewRow row in dGridDetail.SelectedRows)
            {
                list.Add(row.Cells["boxno"].Value.ToString());
            }
            basicSql.getproduceNo((list), dGridDetail.CurrentRow.Cells["orderDetailNo"].Value.ToString());
            Report r = new Report();
            DataTable V_orderproduceTable = new DataTable();
            V_orderproduceTable.Load(basicSql.getproduceNo((list), dGridDetail.CurrentRow.Cells["orderDetailNo"].Value.ToString()));
            DataSet ds = new DataSet();
            ds.Tables.Add(V_orderproduceTable);
            //  ds.Tables.Add(orderProduceList.getproduceByproduceNo(dGridorderProduceList.CurrentRow.Cells["produceNo"].Value.ToString()));
            //  r.Load(@"e:\东华软件项目\报表\orderproduce.frx");
            r.Load(@"\\192.168.0.27\东华软件\报表\packbiaoqian.frx");

            r.RegisterData(ds);
            r.Design();
        }

        private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string id = dGridDetail.Rows[dGridDetail.CurrentRow.Index].Cells[0].Value.ToString();
                DialogResult result = MessageBox.Show("是否删除：" + id + "！", "提示信息", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    dGridDetail.Rows.Remove(dGridDetail.CurrentRow);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void 普通标签ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            foreach (DataGridViewRow row in dGridDetail.SelectedRows)
            {
                list.Add(row.Cells["boxno"].Value.ToString());
            }
            basicSql.getproduceNo((list), dGridDetail.CurrentRow.Cells["orderDetailNo"].Value.ToString());
            Report r = new Report();
            DataTable V_orderproduceTable = new DataTable();
            V_orderproduceTable.Load(basicSql.getproduceNo((list), dGridDetail.CurrentRow.Cells["orderDetailNo"].Value.ToString()));
            DataSet ds = new DataSet();
            ds.Tables.Add(V_orderproduceTable);
            //  ds.Tables.Add(orderProduceList.getproduceByproduceNo(dGridorderProduceList.CurrentRow.Cells["produceNo"].Value.ToString()));
           // r.Load(@"e:\东华软件项目\报表\packbiaoqian.frx");
          r.Load(@"\\192.168.0.27\东华软件\报表\packbiaoqian.frx");

            r.RegisterData(ds);
           // r.Design();
            r.Show();
        }

        private void 河源标签ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            foreach (DataGridViewRow row in dGridDetail.SelectedRows)
            {
                list.Add(row.Cells["boxno"].Value.ToString());
            }
            basicSql.getproduceNo((list), dGridDetail.CurrentRow.Cells["orderDetailNo"].Value.ToString());
            Report r = new Report();
            DataTable V_orderproduceTable = new DataTable();
            V_orderproduceTable.Load(basicSql.getproduceNo((list), dGridDetail.CurrentRow.Cells["orderDetailNo"].Value.ToString()));
            DataSet ds = new DataSet();
            ds.Tables.Add(V_orderproduceTable);
            //  ds.Tables.Add(orderProduceList.getproduceByproduceNo(dGridorderProduceList.CurrentRow.Cells["produceNo"].Value.ToString()));
           // r.Load(@"e:\东华软件项目\报表\packbiaoqianheyuan.frx");
            r.Load(@"\\192.168.0.27\东华软件\报表\packbiaoqianheyuan.frx");

            r.RegisterData(ds);
           // r.Design();
         r.Show();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            state = "新增";
            packMasterTable.Clear();
            textbillNo.Text = "P" + GlobalInfo.Date + "-" + basicSql.getOrderSerail("包装入库单号");
            bindingSourcepackStockInDetail.DataSource = packStockIn.getspackStockInDetailAllBybillNo(textbillNo.Text);
            dGridDetail.DataSource = bindingSourcepackStockInDetail;
            textstockname.Text = "成品仓";
            dGridDetail.AllowUserToAddRows = true;
            this.KeyPreview = true;
            dGridDetail.EditMode = DataGridViewEditMode.EditOnEnter;
            comboBoxdeptNum.Text = "包装部";
            dateTimebillDate.Value = DateTime.Now;
        }

        private void 删除已ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string id = dGridDetail.Rows[dGridDetail.CurrentRow.Index].Cells[0].Value.ToString();
                DialogResult result = MessageBox.Show("是否删除：" + id + "！", "提示信息", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {

                    packStockIn.packStockInDetailDel(id);
                    dGridDetail.Rows.Remove(dGridDetail.CurrentRow);
                }
        }
    }
}
